import tkinter as tk
import pandas as pd
from tkinter import messagebox
from datetime import datetime
from dateutil.relativedelta import relativedelta

class Setting:
    def __init__(self):
        self.url_fileRoomInfo = 'data/RMS_RoomInfo.xlsx'
        self.url_fileTenantInfo = 'data/RMS_Tenant.xlsx'
        self.url_fileRentalInfo = 'data/RMS_Rental.xlsx'
        self.url_filePrice = 'data/RMS_Price.xlsx'
        warterPrice = 0
        electricPrice = 0

    # 重载输入框内容，先清空再写入
    def reloadENT(self, ENT, text):
        ENT.delete(0, tk.END)
        ENT.insert(0, text)

    #删除内容
    def del_row_to_excel(self, file_path, row_data, sheet_name):
        df = pd.read_excel(file_path, sheet_name=sheet_name, engine='openpyxl', header=None)
        try:
            row_index = df.index[df[0] == row_data].tolist() #获取需要删除房间索引
        except Exception as e:
            messagebox.showwarning("提示", "需要删除的内容不存在！")
            print(f"发生了一个错误：{e}")
        else:
            df = df.drop(row_index) #根据索引删除数据
            # 将DataFrame对象写入特定的工作表和行
            df.to_excel(file_path, index=False, header=False, sheet_name=sheet_name, startrow=0)
            messagebox.showwarning("提示", "已删除成功！")
    # 获取房间列表
    def roomList(self, url, sheet_name):
        line = pd.read_excel(url, sheet_name=sheet_name, engine='openpyxl', header=0)
        la = line.iloc[:, 0]
        return sorted(la)

    def get_warterPrice(self):
        return Setting.warterPrice

    def set_warterPrice(self, warterP):
        Setting.warterPrice = warterP

    def get_electricPrice(self):
        return Setting.electricPrice

    def set_electricPrice(self, electricP):
        Setting.electricPrice = electricP

    def monthList(self):
        # 获取当前时间
        current_time = datetime.now()
        # 初始化一个空列表来存储格式化的日期
        date_list = []
        # 循环过去24个月
        for i in range(1, 25):
            # 计算当前月的前i个月的时间
            past_time = current_time - relativedelta(months=i)
            # 格式化日期为 yyyymm
            date_str = past_time.strftime('%Y%m')
            # 将格式化的日期添加到列表中
            date_list.append(date_str)
        # 对列表进行排序（默认升序）
        date_list.sort()
        # 由于我们需要倒序，所以对排序后的列表进行逆序
        date_list.reverse()
        return date_list

    def number_to_chinese(self, num):
        chinese_numbers = "零一二三四五六七八九"
        units = ["", "十", "百", "千", "万", "十", "百", "千", "亿"]
        num_str = str(num)
        length = len(num_str)
        chinese_str = ""
        i = 0
        zero = False
        while i < length:
            n = int(num_str[i])
            if n == 0:
                zero = True
            else:
                if zero:
                    chinese_str += "零"
                    zero = False
                chinese_str += chinese_numbers[n] + units[length - i - 1]
            i += 1
        chinese_str += "元整"
        return chinese_str